import { useUserStore } from '@/stores/userStore'
import { createRouter, createWebHistory } from 'vue-router'
import RoleRoute from '@/router/role' // 角色权限动态导入的路由
import { ref } from 'vue'

const secondJump = ref(true)
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/home/HomeView.vue'),
      meta: { title: '首页' }
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/LoginView.vue'),
      meta: { notLogin: true, title: '登录' },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/register/RegisterView.vue'),
      meta: { notLogin: true, title: '注册' },
    },
    {
      path: '/:pathMatch(.*)*',
      name: 'notFound',
      component: () => import('@/views/NotFound.vue'),
      meta: { title: '404页面不存在' }
    },
  ],
})

// 路由前置守卫
router.beforeEach((to) => {
  // 在守卫里面使用pinia确保pinia初始化了
  const store = useUserStore()

  // 如果没有notlogin字段标识, 表示需要登录验证
  if (!to.meta.notLogin) {
    // 检查本地存储中是否含有相关token
    if (!store.user) return '/login'
  }
  // 判断是否有title
  if (to.meta.title) {
    // 修改标题
    document.title = to.meta.title as string
  }
  // 动态导入相关权限的路由
  if (store.jurisdiction && store.user && store.user.routers) {
    // console.log(RoleRoute)
    // router.addRoute('home', RoleRoute[0])
    RoleRoute.forEach((item) => {
      if (store.user!.routers.includes(item.path)) {
        router.addRoute('home', item)
        // console.log(item)
      }
    })
    // console.log(router)
    // 进行二次跳转, 动态导入的路由在页面第一次加载是还没有导入
    if (secondJump.value) {
      secondJump.value = false
      return store.currentRouteMenu
    }
  }
})

export default router
